import { createStore } from "vuex";
import { adminInfoAPI } from "../request/api";
import userInfo from "./userInfo";
interface Store {
  menus: MenusObj[];
  // username: string;
  isHiddenNav: boolean;
}
interface MenusObj {
  parentId: number;
  id: number;
  name: string;
  children?: MenusObj[];
}
interface NewMenus {
  [key: string]: MenusObj;
}

const store = createStore<Store>({
  //   state: {},
  //可以写成函数形式
  state() {
    return {
      menus: [],
      //左侧导航是否缩小
      isHiddenNav: false,
    };
  },
  getters: {
    getNewMenus(state) {
      const menus = state.menus;
      let newMenus: NewMenus = {};
      for (let i = 0; i < menus.length; i++) {
        //一级菜单
        if (menus[i].parentId === 0) {
          newMenus[menus[i].id] = { ...menus[i], ...newMenus[menus[i].id] };
        } else {
          //二级菜单
          const subMenu = menus[i];
          //二级才对对应的一级菜单
          newMenus[subMenu.parentId] = newMenus[subMenu.parentId] || {};
          newMenus[subMenu.parentId].children =
            newMenus[subMenu.parentId].children || [];
          //添加二级菜单对应的一级菜单上的children
          newMenus[subMenu.parentId].children!.push(subMenu);
        }
      }
      return newMenus;
    },
    PermissionMenus(state) {
      return state.menus.map((item) => item.name);
    },
  },
  mutations: {
    updateMenus(state, menus) {
      state.menus = menus;
    },
    updateIsHiddenNav(state) {
      state.isHiddenNav = !state.isHiddenNav;
    },
  },
  actions: {
    getAdminInfo({ state, commit }) {
      //获取登录用户信息
      return adminInfoAPI().then((res) => {
        if (res.code === 200) {
          commit("updateMenus", res.data.menus);
          //.then里返回值就是一个成功的promise，可以提供给。then链式调用
          return res.data;
        } else {
          return Promise.reject(res);
        }
      });
    },
  },
  modules: { userInfo },
});

export default store;
